import sys
import time
import json
from datetime import datetime
from selenium import webdriver
from selenium.common import exceptions
from selenium.webdriver.chrome.options import Options
import urllib.parse
from mongoengine import *
from selenium.webdriver.common.action_chains import ActionChains

whiteList = ['-101','-100','4450443968889831','4044671657000761','3263330414','5581785513']


class privateuser(Document):
    nickname = StringField()
    gender = IntField()
    city = StringField()
    followerCount = IntField()
    uid = StringField()
    addTime = DateTimeField()
    accountUid = StringField()
    accountName = StringField()
    updatetime = DateTimeField()
    postCount = IntField()
    fansCount = IntField()
    searched = IntField()
    privateList = ListField()
    isFans = IntField()
    isClicked = IntField()
    isDelete = IntField()
    firstchprivatedate = DateTimeField()
    meta = {
        'strict':False
    }


class newprivateuser(Document):
    nickname = StringField()
    gender = IntField()
    city = StringField()
    followerCount = IntField()
    uid = StringField()
    addTime = DateTimeField()
    accountUid = StringField()
    accountName = StringField()
    updatetime = DateTimeField()
    postCount = IntField()
    fansCount = IntField()
    searched = ListField()
    firstClickUser = ListField()
    allClickUser = ListField()
    isClicked = IntField()
    isDelete = IntField()
    meta = {
        'strict':False
    }


class myprivateaccounts(Document):
    name = StringField()
    uid = StringField()
    addTime = DateTimeField()
    updatetime = DateTimeField()
    isDelete = IntField()
    meta = {
        'strict':False
    }


class chatlistuser(Document):
    nickname = StringField()
    gender = IntField()
    city = StringField()
    followerCount = IntField()
    uid = StringField()
    addTime = DateTimeField()
    accountUid = StringField()
    accountName = StringField()
    updatetime = DateTimeField()
    postCount = IntField()
    fansCount = IntField()
    searched = ListField()
    firstClickUser = ListField()
    allClickUser = ListField()
    isClicked = IntField()
    isDelete = IntField()
    lastShowDate = DateTimeField()
    error = IntField()
    meta = {
        'strict':False
    }

class showchatlist(Document):
    accountName = StringField()
    uidlist = ListField()
    isDelete = IntField()
    updatetime = DateTimeField()
    needsearchlist = ListField()
    meta = {
        'strict':False
    }

class refreshuserchat(Document):
    isDelete = IntField()
    addTime = DateTimeField()
    updatetime = DateTimeField()
    uid = StringField()
    searched = ListField()
    accountUid = StringField()
    accountName = StringField()
    meta = {
        'strict':False
    }




def NewDriver(accountName):
    chrome_options = Options()
    chrome_options.add_argument("user-data-dir=" + path2 + 'privatelist' + accountName)
    # chrome_options.add_argument("user-data-dir=" + path2 + 'searchprivate' + accountName)
    driver = webdriver.Chrome(path, options=chrome_options)
    driver.maximize_window()
    return driver

    

def readUserInfoImList(session):
    info = session.find_element_by_class_name('name')
    nickName = info.find_element_by_class_name('usrn').get_attribute('textContent')
    uid = info.find_element_by_class_name('hidden').get_attribute('textContent')
    top = 0
    toptags = info.find_elements_by_class_name('toptag')
    if len(toptags) != 0:
        top = 1
    date = session.find_elements_by_class_name('time')[-1].get_attribute('textContent')
    if uid not in whiteList:
        user = chatlistuser.objects(uid=uid,accountUid=accountList[index]["uid"])
        if len(user)==0:
            print(nickName,uid,top,date)
            newdata = chatlistuser(
                nickname = nickName, 
                uid = uid,
                searched = [],
                addTime = datetime.now(),
                accountUid = accountList[index]["uid"],
                accountName = accountList[index]["name"],
                updatetime = datetime.now(),
                isDelete = 0,
                isClicked = 0,
                lastShowDate = datetime.now()
            )
            newdata.save()
        else:
            user = chatlistuser.objects.get(uid=uid,accountUid=accountList[index]["uid"])
            user.updatetime = datetime.now()
            # user.isDelete = 1
            user.save()
            # newdata = chatlistuser(
            #     nickname = nickName, 
            #     uid = uid,
            #     searched = [],
            #     addTime = datetime.now(),
            #     accountUid = accountList[index]["uid"],
            #     accountName = accountList[index]["name"],
            #     updatetime = datetime.now(),
            #     isDelete = 0,
            #     isClicked = 0,
            #     lastShowDate = datetime.now()
            # )
            # newdata.save()
    if "微博" not in nickName:
        return uid,date

# def chatList():
#     chatUidList = []
#     chatList = driver0.find_elements_by_class_name('sessionlist')
#     showlist = showchatlist.objects.get(accountName = accountName)
#     # chatList.reverse()
#     if len(chatList)>0:
#         for session in chatList:
#             try:
#                 uid,date = readUserInfoImList(session)
#                 chatUidList.append(uid)
#                 if uid not in whiteList:
#                     try:
#                         if weibochatdict[uid]!= date:
#                             weibochatdict[uid] = date
#                             print(uid,'!=')
#                             if uid not in showlist.needsearchlist:
#                                 tempuserlist = refreshuserchat.objects(uid = uid)
#                                 if len(tempuserlist) == 0:
#                                     newdata = refreshuserchat(
#                                         uid = uid,
#                                         searched = [],
#                                         addTime = datetime.now(),
#                                         updatetime = datetime.now(),
#                                         accountUid = accountList[index]["uid"],
#                                         accountName = accountList[index]["name"],
#                                         isDelete = 0,
#                                     )
#                                     newdata.save()
#                                 else:
#                                     tempuser = refreshuserchat.objects.get(uid=uid),
#                                     tempuser.updatetime = datetime.now(),
#                                     tempuser.searched = [],
#                                     tempuser.save()

#                                 # showlist.needsearchlist.insert(0, uid)
#                     except:
#                         weibochatdict[uid] = date
#                         print(uid,'new')
#                         if uid not in showlist.needsearchlist:
#                             tempuserlist = refreshuserchat.objects(uid = uid)
#                             if len(tempuserlist) == 0:
#                                 newdata = refreshuserchat(
#                                     uid = uid,
#                                     searched = [],
#                                     addTime = datetime.now(),
#                                     #updatetime = datetime.now(),
#                                     accountUid = accountList[index]["uid"],
#                                     accountName = accountList[index]["name"],
#                                     isDelete = 0,
#                                 )
#                                 newdata.save()
#                             else:
#                                 tempuser = refreshuserchat.objects.get(uid=uid),
#                                 #tempuser.updatetime = datetime.now(),
#                                 tempuser.searched = [],
#                                 tempuser.save()
#                             # showlist.needsearchlist.insert(0, uid)
#             except Exception as e:
#                 print(str(e),'error')
#     showlist.uidlist = chatUidList
#     # if len(showlist.uidlist) > 14:
#     showlist.save()



def chatList():
    chatUidList = []
    chatList = driver0.find_elements_by_class_name('sessionlist')
    # chatList.reverse()
    if len(chatList)>0:
        for session in chatList:
            try:
                uid,date = readUserInfoImList(session)
                chatUidList.append(uid)
            except Exception as e:
                print(str(e),'error')
    showlist = showchatlist.objects.get(accountName = accountName)
    showlist.uidlist = chatUidList
    # if len(showlist.uidlist) > 14:
    showlist.save()
                                                                                                          

if __name__ == '__main__':
    global accountName
    global needsearchuid
    weibochatdict = {}
    index = int(sys.argv[1])
    # accountName = sys.argv[1]
    # accountUid = sys.argv[2]
    # accountList = [{"accountUid":accountUid,"accountName":accountName}]
    mode = 1
    path = 'd:/work/weiboprivate/python/chromedriver.exe'
    path2 = 'd:/work/weiboprivate/profile/'
    if mode == 1:
        path = 'd:/weiboprivate/python/chromedriver.exe'
        path2 = 'd:/weiboprivate/profile/'
        connect('weibo', host='1.15.92.12', port=27817)
        # connect('weibo', host='localhost', port=27017)
    else:
        connect('weibo', host='1.15.92.12', port=27817)
        # connect('weibo', host='localhost', port=27017)

    accountList = myprivateaccounts.objects(isDelete=0)
    accountName = accountList[index]['name']
    accountUid = accountList[index]['uid']
    
    driver0 = NewDriver(accountName)
    driver0.get("https://weibo.com")
    driver0.get("https://api.weibo.com/chat")

    # page_source = ""
    while True:
        time.sleep(1)
        chatList()
        driver0.get("https://api.weibo.com/chat")
        # try:
        #     if page_source != driver0.page_source():
        #         page_source = driver0.page_source()
        #         print("run")
            


        